package com.example.project.projectspringcloud.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Json字符串处理工具
 * Created by Wangys 2018年4月17日
 */
public class JsonUtil {

    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 工具类禁止实例化
     */
    private JsonUtil() {
    }

    /**
     * json转Map
     */
    public static Map<String, ?> json2Map(String json) {
        return fromJson(json, Map.class);
    }

    public static Map<String, ?> obj2Map(Object object) {
        String s = obj2Json(object);
        return json2Map(s);
    }

    /**
     * json转list
     */
    public static List json2List(String json) {
        return fromJson(json, new TypeReference<List<String>>() {
        });
    }

    /**
     * 把实体Bean、Map对象、数组、列表集合转换成Json格式的字符串
     */
    public static <T> T fromJson(String json, TypeReference clazz) {
        try {
            return OBJECT_MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return OBJECT_MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 把实体Bean、Map对象、数组、列表集合转换成Json格式的字符串
     */
    public static String obj2Json(Object obj) {
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
